package com.zyj.core.builder;

import com.zyj.core.config.Configuration;
import com.zyj.core.config.MappedStatement;
import com.zyj.core.sqlsource.SqlSource;
import org.dom4j.Element;

public class XMLStatementBuilder {

    private Configuration configuration;

    public XMLStatementBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * <select id="queryUserByParams2"
     * 		resultType="com.zyj.mybatis.po.User"
     * 		statementType="prepared">
     * 		SELECT * FROM user WHERE sex = #{sex}
     * 	</select>
     */

    /**
     * 解析statement标签
     *
     * @param namespace
     * @param selectElement
     */
    public void parseStatement(String namespace, Element selectElement) {
        // 解析id属性
        String id = selectElement.attributeValue("id");
        // 拼接得到statementId，即mappedStatementMap中的key
        String statementId = namespace + "." + id;
        // 解析resultType属性
        String resultType = selectElement.attributeValue("resultType");
        // 解析statementType属性
        String statementType = selectElement.attributeValue("statementType");

        // 封装SqlSource数据 即 SELECT * FROM user WHERE sex = #{sex} 这一条sql就会被封装成一个sqlSource对象
        // 传入整个select标签
        SqlSource sqlSource = createSqlSource(selectElement);

        // 封装MappedStatement
        MappedStatement mappedStatement = new MappedStatement(statementId, resultType, statementType, sqlSource);

        configuration.addMappedStatement(statementId, mappedStatement);

    }

    private SqlSource createSqlSource(Element selectElement) {

        // 使用XMLScriptBuilder构建器来解析sql并得到SqlSource对象
        XMLScriptBuilder scriptBuilder = new XMLScriptBuilder();
        // 传入整个select标签
        SqlSource sqlSource = scriptBuilder.parseScriptNode(selectElement);
        return sqlSource;
    }

}
